package com.yuand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuand.entity.LoginUser;
import com.yuand.entity.SysMenu;
import com.yuand.entity.SysUser;
import com.yuand.mapper.SysMenuMapper;
import com.yuand.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName: UserDetailsServiceImpl
 * @Author: yuandong
 * @Date 2022/1/14 15:12
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("进入UserDetailsServiceImpl中的loadUserByUsername()方法了，在这里查询用户的权限信息......");
        //根据用户名查询用户信息
       /* LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser user = userMapper.selectOne(wrapper);*/

        SysUser user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("username",username));

        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //TODO  这里需要将查询用户的角色和菜单权限并 添加到LoginUser中
        List<String> prems = this.sysPermissionService.getMenuPermission(user);

        //封装成UserDetails对象返回
        LoginUser loginUser = new LoginUser(user, prems);

        return loginUser;
    }
}
